﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;
using System.IO;
using Newtonsoft.Json.Linq;

namespace SuperMan
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        //格式化json字符串
        string convertJsonString(string str)
        {
            object obj = null;
            JsonSerializer serializer = new JsonSerializer();
            try
            {
                TextReader tr = new StringReader(str);
                JsonTextReader jtr = new JsonTextReader(tr);
                obj = serializer.Deserialize(jtr);
            }
            catch (Exception es)
            {
                MessageBox.Show(es.Message);
                return null;
            }

            if (obj != null)
            {
                StringWriter textWriter = new StringWriter();
                JsonTextWriter jsonWriter = new JsonTextWriter(textWriter)
                {
                    Formatting = Formatting.Indented,
                    Indentation = 4,
                    IndentChar = ' '
                };
                serializer.Serialize(jsonWriter, obj);
                return textWriter.ToString();
            }
            else
            {
                return null;
            }
        }
      

        private void jsonTree_AfterSelect(object sender, TreeViewEventArgs e)
        {
            //  jsonTree.SelectedNode.Text.ToString;
            //JsonTreeNode jtn = (JsonTreeNode)jsonTree.SelectedNode;

            //   this.jsonToolStripStatusLabel.Text = jtn.jsonObject.Value<String>();
            //  dynamic model = JsonConvert.DeserializeObject(json);
            //try
            //{
            //    object _obj = JsonConvert.DeserializeObject(jtn.JsonValue);
            //    if (_obj.GetType() == typeof(JObject))
            //    {
            //        Dictionary<string, string> data = JsonConvert.DeserializeObject<Dictionary<string, string>>(jtn.JsonValue);
            //        this.jsonDataGridView.DataSource = (from v in data
            //                                            select new
            //                                            {
            //                                                Key = v.Key,
            //                                                Value = v.Value
            //                                            }).ToArray();
            //    }
            //}
            //catch (Exception ex)
            //{

            //}

            ;
            //MessageBox.Show(jsonTree.SelectedNode.Text.ToString());
        }


        private void jsonFormatButtonClick(object sender, EventArgs e)
        {

            doformat();
        }


        private void openTreeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.jsonTree.ExpandAll();
        }

        private void closeTreeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.jsonTree.CollapseAll();
        }

        private void jsonOpenFileToolStripButton_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Multiselect = false;//该值确定是否可以选择多个文件
            dialog.Title = "请选择文件夹";
            dialog.Filter = "所有文件(*.*)|*.*";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {

                String jsonfile = "";
                String line = "";
                using (StreamReader sr = new StreamReader(dialog.FileName))
                {
                    while ((line = sr.ReadLine()) != null)
                    {
                        jsonfile = jsonfile + line;
                    }
                    sr.Close();
                }

                jsonTextBox.Text = jsonfile;

                // do something            textBox.Text = dialog.FileName; 
            }
        }

        void jsonTextBox_LostFocus(object sender, System.EventArgs e)
        {
            //Console.WriteLine("......");
        }

        private void doformat(object sender, KeyEventArgs e)
        {
            if ((e.KeyCode == Keys.F) && e.Control)
                doformat();
        }

        private void doformat()
        {
            string _str = jsonTextBox.Text.ToString();
            string str = convertJsonString(_str);
            if (str != null)
            {
                jsonTextBox.Text = str;
                //tree view 绑定
                jsonTree.Nodes.Clear();
                JsonTreeNode tree = new JsonTreeNode("{}");
              JObject jo=  (JObject)JsonConvert.DeserializeObject(str);

              tree.jsonObject = jo;
              //  tree.JsonValue = str;

              paresCheld(ref tree, jo);
              //  AddTreeChildNode(ref tree,_str);
               // tree.JsonObject =;
                jsonTree.Nodes.Add(tree);
                jsonTree.ExpandAll();
            }
        }
        public void paresCheld(ref JsonTreeNode node, JToken jt)
        {
            foreach (JToken child in jt.Children())
            {
                var property = child as JProperty;
                if (property != null)
                {
                  
                    JsonTreeNode snode= new JsonTreeNode();
                    snode.jsonObject = property;
                    node.Nodes.Add(snode);
                    snode.jKey = property.Name;
                    snode.Text = property.Name;    
                    if (property.Value.Type != JTokenType.Object && property.Value.Type != JTokenType.Array)
                    {
                        snode.Text = property.Name + ": " + property.Value.ToString();
                        snode.ImageIndex = 1;
                        snode.SelectedImageIndex = 1;
                        snode.jValue = property.Value.ToString();
                        
                    }
                    else if (property.Value.Type == JTokenType.Array)
                    {
                        JArray array = (JArray)property.Value;
                        for (int i = 0; i < array.Count; i++)
                        {
                            JsonTreeNode ssnode = new JsonTreeNode("["+i+"]");
                            snode.Nodes.Add(ssnode);
                            ssnode.jsonObject = (JToken)array[i];
                            paresCheld(ref ssnode, array[i]);
                        }
                    }
                    else if (property.Value.Type == JTokenType.Object)
                    {
                        foreach (var item in property)
                        {
                            paresCheld(ref snode, item);
                        }
                    }                   
                }
            }
        }

         void updateJsonTreeNodeValue(object sender, TreeNodeMouseClickEventArgs e)
        {
            JsonTreeNode jtn = (JsonTreeNode)jsonTree.SelectedNode;
            if (jtn.jKey!=null)
            {
                JsonNodeInput jni = new JsonNodeInput(jtn);
                //    JsonNodeInput jni = new JsonNodeInput(jtn);
                if (DialogResult.OK == jni.ShowDialog()) {

                    foreach (var tn in jsonTree.Nodes)
                    {
                        if (tn.GetType() == typeof(JsonTreeNode))
                        {
                            JsonTreeNode _jtn = (JsonTreeNode)tn;
                             Console.WriteLine( convertJsonString ( _jtn.jsonObject.ToString()));
                        }
                        
                    }
               
                    ;
                }
            }

        }

        private void tree2JsonButton_Click(object sender, EventArgs e)
        {
            // jsonTree.Nodes
        }


    }
}
